/**
 * @author tsdy
 * @description 资源管理中心的父类
 */

import * as PIXI from 'pixi.js';
import {load } from '../lib/loader';
import { ResourceCenterConfig, ResourceUrl } from '../typings/resource';

class Resource {
    protected texture: Record<string, PIXI.Texture>;
    protected textures: Record<string, Array<PIXI.Texture>>;
    protected audio: Record<string, HTMLAudioElement>;
    private ImageResource: Array<ResourceUrl> | undefined;
    private MusicResource: Array<ResourceUrl> | undefined;
    constructor(config: ResourceCenterConfig) {
        this.ImageResource = config.ImageResource;
        this.MusicResource = config.MusicResource;
        this.texture = {};
        this.textures = {};
        this.audio = {};
    }
    protected async initResource() {
        await this.load();

    }
    private async load() {
        await this.loadImage();
        await this.loadMusic();
    }
    private async loadImage() {
        let resources: Partial<Record<string, PIXI.LoaderResource>>;
        if (this.ImageResource) {
            resources = await load(this.ImageResource);
            Object.keys(resources).forEach(name => {
                // 如果加载的是一个雪碧图，textures就不为空
                if (resources[name]?.textures) {
                    this.textures[name] = [];
                    Object.values(<Record<string, PIXI.Texture>>resources[name]?.textures).forEach(texture => {
                        this.textures[name].push(texture);
                    })
                    
                } else if (resources[name]?.texture) {
                    this.texture[name] = <PIXI.Texture>resources[name]?.texture;
                }
            })
        }
    }
    private async loadMusic() {
        if (this.MusicResource) {

            let resources: Partial<Record<string, PIXI.LoaderResource>>;
            resources = await load(this.MusicResource);
            console.log(resources)
            Object.values(this.MusicResource).forEach(item => {
                this.audio[item.name] = resources[item.name]?.data;
            })
        }
    }
}



export default Resource;